package com.boxing.dao;

import com.boxing.utils.JdbcUtilsDRI;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BaseDao {
    QueryRunner queryRunner = new QueryRunner();

    /**
     * 查询唯一的结果
     * @param sql
     * @param t
     * @param params
     * @return
     * @param <T>
     */
    public <T> T queryOne(String sql,Class<T> t, Object ...params){
        Connection connection = JdbcUtilsDRI.getConnection();
        try {
            // 内醒
            return queryRunner.query(connection, sql, new BeanHandler<T>(t), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtilsDRI.close(connection);
        }
        return null;
    }

    /**
     * 查询列表
     * @param sql
     * @param t
     * @param params
     * @return
     * @param <T>
     */
    public <T> List<T> queryList(String sql, Class<T> t, Object ...params){
        Connection connection = JdbcUtilsDRI.getConnection();
        try {
            return queryRunner.query(connection, sql, new BeanListHandler<T>(t), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtilsDRI.close(connection);
        }
        return null;
    }

    public int insertData(String sql, Object ...params){
        Connection connection = JdbcUtilsDRI.getConnection();
        try {
            return queryRunner.update(connection, sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtilsDRI.close(connection);
        }
        return -1;
    }

    /**
     * 查询某一个值
     * @param sql
     * @param params
     * @return
     */
    public Object queryValue(String sql, Object ...params){
        Connection connection = JdbcUtilsDRI.getConnection();
        try {
            return queryRunner.query(connection, sql, new ScalarHandler<>(), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtilsDRI.close(connection);
        }
        return null;
    }
}
